package com.plm.htmlfiledownload.common;

import java.io.FileOutputStream;
import java.io.IOException;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Set;

import com.itextpdf.text.DocumentException;

import com.itextpdf.text.pdf.AcroFields;

import com.itextpdf.text.pdf.BaseFont;

import com.itextpdf.text.pdf.PdfReader;

import com.itextpdf.text.pdf.PdfStamper;
import org.springframework.util.ResourceUtils;

/**
 * @ClassName: PDFUtil
 * @Description: PDFUtil
 * @Author pengliming
 * @Date 14:00 2019/7/15
 */
public class PDFUtil {

    public static void main(String [] args){
        //1 准备要填充的数据
        Map paraMap = new HashMap();
        paraMap.put("XM", "付测试");
        paraMap.put("XB", "男");
        paraMap.put("MZ", "汉");
        paraMap.put("CSRQ", "20190303");
        paraMap.put("SFZBH", "111111111111111111");
        pdfCreate("C:\\Users\\花爸爸\\Desktop\\pdf\\my_blspb.PDF",paraMap);
    }

    /**
    *@Description 生成pdf文件
    *@Param lastPath  pdf文件生成路径  paraMap 表单参数
    *@Author pengliming
    *@Date
    */
    public static void pdfCreate(String lastPath,Map<String,Object> paraMap){
        try {
            //获取项目根路径
            String basePath = ResourceUtils.getURL("classpath:").getPath();
            String filePath = basePath + "pdfModel/pdfModel.pdf";
            //2 读入pdf表单
            PdfReader reader = new PdfReader(filePath);
            //3 根据表单生成一个新的pdf
            PdfStamper ps = new PdfStamper(reader,new FileOutputStream(lastPath));
            //4 获取pdf表单
            AcroFields s = ps.getAcroFields();
            //5给表单添加中文字体 这里采用系统字体。不设置的话，中文可能无法显示
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            s.addSubstitutionFont(bf);
            //6遍历pdf表单表格，同时给表格赋值
            Map fieldMap = s.getFields();
            Set set = fieldMap.entrySet();
            Iterator iterator = set.iterator();
            while(iterator.hasNext()){
                Entry entry = (Entry) iterator.next();
                String key = (String)entry.getKey();
                if(paraMap.get(key)!=null){
                    s.setField(key, ""+paraMap.get(key.toUpperCase()));
                }
            }
            ps.setFormFlattening(true); // 这句不能少
            ps.close();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}